﻿using Base.Structure.Application.Dto;
using Base.Structure.Application.Interfaces;
using Base.Structure.Cache;
using Base.Structure.MessageQueue;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Base.Structure.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly ICacheHelper _cacheHelper;
        private readonly IMessageProducer _messageProducer;

        public UserController(IUserService userService, ICacheHelper cacheHelper, IMessageProducer messageProducer)
        {
            _userService = userService;
            _cacheHelper = cacheHelper;
            _messageProducer = messageProducer;
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<UserDto>> GetUser(int id)
        {
            var cacheKey = $"User_{id}";
            var user = await _cacheHelper.GetCacheAsync<UserDto>(cacheKey);

            if (user == null)
            {
                user = await _userService.GetUserByIdAsync(id);
                await _cacheHelper.SetCacheAsync(cacheKey, user, TimeSpan.FromMinutes(5));
            }

            return Ok(user);
        }

        [HttpPost]
        public async Task<IActionResult> CreateUser([FromBody] UserDto userDto)
        {
            var userId = await _userService.CreateUserAsync(userDto);

            // 发送消息到消息队列
            _messageProducer.SendMessage($"User {userId} created.");

            return CreatedAtAction(nameof(GetUser), new { id = userId }, userDto);
        }
    }
}
